package com.happyrecyclingstation.service.impl;

import com.happyrecyclingstation.dto.MessageDto;
import com.happyrecyclingstation.entity.Message;
import com.happyrecyclingstation.mapper.MessageMapper;
import com.happyrecyclingstation.service.MessageService;
import com.happyrecyclingstation.utils.CurrentHolder;
import com.happyrecyclingstation.utils.GenerateSessionId;
import com.happyrecyclingstation.vo.ContactVO;
import com.happyrecyclingstation.vo.MessageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    /**
     * 通过id获取联系人列表
     * @param id
     * @return
     */
    @Override
    public List<ContactVO> getContact(Integer id) {
        List<ContactVO> contactList = messageMapper.getContact(id);
        return contactList;
    }

    /**
     * 获取联系人历史消息
     * @param id
     * @return
     */
    @Override
    public List<MessageVO> getHistoryMsg(Integer id) {
        //生成session_id
        Integer currentId = CurrentHolder.getCurrentId();
        String sessionId = GenerateSessionId.generateSessionId(id, currentId);
        //通过会话id查询历史信息
        List<MessageVO> messageList = messageMapper.getHistoryMsg(sessionId);
        return messageList;
    }

    /**
     * 保存消息
     * @param messageDto
     */
    @Override
    public void saveMessage(MessageDto messageDto) {
        Message message = new Message();
        // 拷贝属性
        BeanUtils.copyProperties(messageDto, message);
        message.setSendTime(LocalDateTime.now());
        messageMapper.saveMessage(message);
    }

    /**
     * 判断是否为联系人
     * @param hr
     * @return
     */
    @Override
    public Integer isContact(Integer hr) {
        Integer currentId = CurrentHolder.getCurrentId();
        //查询是否建立联系关系
        Integer isContact = messageMapper.selectIsContact(currentId, hr);
        //如果建立好友关系直接返回1
        if (isContact != 0){
            return 1;
        }
        //如果没有建立好友关系则建立好友联系返回0
        messageMapper.saveContact(currentId, hr);
        return 0;
    }
}
